package com.css.common.core.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.common.core.exception.ServiceException;
import feign.FeignException;
import feign.Logger.Level;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 发票feign配置
 * @Title: FpkjFeignConfig
 * @Author xlw
 * @Package com.invoice.config
 * @Date 2024/7/17 15:37
 */
public class FpkjFeignConfig {

    @Value("${fpkj.appkey}")
    private String appkey;

    @Value("${fpkj.appscret}")
    private String appscret;

    /**
     * 纳税人识别号
     */
    private final String NSRSBH = "nsrsbh";

    @Bean
    public Level feignLogLevel(){
        return Level.FULL;
    }

    @Bean
    public RequestInterceptor interceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                Map<String, Collection<String>> headers = template.headers();
                if (MapUtil.isEmpty(headers) || !headers.containsKey(NSRSBH)) {
                    throw new ServiceException("请求头未找到" + NSRSBH);
                }

                Collection<String> c = headers.get(NSRSBH);
                String nsrsbhHeader = c.stream().collect(Collectors.joining());
                String ts = String.valueOf(System.currentTimeMillis());
                String md5 = encryption(nsrsbhHeader, ts);
                //设置请求头
                template
                        .header("appKey", appkey)
                        .header("md5", md5)
                        .header("ts", ts);
            }
        };
    }

    @Bean
    public Decoder decoder() {
        return new Decoder() {
            @Override
            public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
                String content = IoUtil.read(response.body().asInputStream(), CharsetUtil.UTF_8);
                JSONObject jsonObject = JSONObject.parseObject(content);
                if(jsonObject.get("data") instanceof JSONObject){
                    JSONObject data = jsonObject.getJSONObject("data");
                    jsonObject.remove("data");
                    if(CollectionUtil.isNotEmpty(data)) {
                        jsonObject.putAll(data);
                    }
                }
                Object result = jsonObject.toJavaObject(type);
                return result;
            }
        };
    }

    private String encryption(String nsrsbh, String ts) {

        //拼接 appkey+appscret+nsrsbh
        StringBuilder builder = new StringBuilder();
        builder
                .append(appkey)
                .append(appscret)
                .append(nsrsbh);
        String str = builder.toString();
        //生成md5
        String md5Str = SecureUtil.md5(str);
        //拼接md5+时间戳
        String str2 = StrUtil.concat(true, md5Str, ts);
        //加密(md5+时间戳)
        String result = SecureUtil.md5(str2);
        return result;
    }

}
